(ns util)
(import '(java.net URL))
(import '(java.io DataInputStream BufferedReader InputStreamReader))

(defn get-proxy-settings []
  (let [http-proxy (System/getenv "http_proxy")]
    (if (nil? http-proxy)
      nil
      (let [[auth proxy] (.split http-proxy "@")
            [host port] (.split proxy ":")
            auth1 (last (.split auth "//"))
            [user pass] (.split auth1 ":")]
        {:user user :pass pass :host host :port port}))))

(defn set-proxy
  ([uc proxy-settings]
     (let [encoder (sun.misc.BASE64Encoder. )
           auth (. encoder encode (. (str (proxy-settings :user)
                                          ":" (proxy-settings :pass)) getBytes))]
       (do
         (. (. System getProperties) put "proxySet" "true")
         (. (. System getProperties) put "proxyHost" (proxy-settings :host))
         (. (. System getProperties) put "proxyPort" (proxy-settings :port))
         (. uc (setRequestProperty "Proxy-Authorization" (str "Basic " auth)))))))

(defn fetch-url
  [u]
  (let [uc (. (URL. u) openConnection)
        a (set-proxy uc (get-proxy-settings))
        r (BufferedReader. (InputStreamReader.
                            (DataInputStream. (. uc getInputStream))))]
    (loop [rs [] line (. r readLine)]
      (if (nil? line)
        rs
        (recur (conj rs line) (. r readLine))))))
        
